/*
 * Filename:    AuditDispatchServiceImpl.java
 * Copyright:   2014 中国平安保险（集团）股份有限公司 版权所有
 * Company:     平安科技养老险及健康险系统开发部
 * Create at:   2014-11-11
 */
package com.paic.mhis.hcpms.audit.biz.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.paic.mhis.common.base.intergration.dao.CommonDAO;
import com.paic.mhis.core.auth.biz.service.Authority;
import com.paic.mhis.core.auth.biz.service.UserDetails;
import com.paic.mhis.hcpms.audit.biz.service.AuditWorkFlowService;
import com.paic.mhis.hcpms.audit.biz.service.IAuditDispatchService;
import com.paic.mhis.hcpms.audit.biz.service.ICaseCommonService;
import com.paic.mhis.hcpms.audit.constants.AuditConstants;
import com.paic.mhis.hcpms.audit.dao.AuditDispatchDao;
import com.paic.mhis.hcpms.audit.dao.AuditOpinionDao;
import com.paic.mhis.hcpms.audit.dto.AuditCodeDictionary;
import com.paic.mhis.hcpms.audit.dto.AuditDispatchParamter;
import com.paic.mhis.hcpms.audit.dto.AuditDispatchProblemDTO;
import com.paic.mhis.hcpms.audit.dto.AuditDispatchRequestDTO;
import com.paic.mhis.hcpms.audit.dto.AuditDispatchResponseDTO;
import com.paic.mhis.hcpms.audit.dto.AuditDispatchUserRequestDTO;
import com.paic.mhis.hcpms.audit.dto.AuditDispatchUserResponseDTO;
import com.paic.mhis.hcpms.audit.dto.AuditInsuranceInfoDTO;
import com.paic.mhis.hcpms.audit.dto.AuditMedicalInfoDTO;
import com.paic.mhis.hcpms.audit.dto.AuditOpinionDTO;
import com.paic.mhis.hcpms.audit.dto.AuditProblemsDTO;
import com.paic.mhis.hcpms.audit.dto.AuditTargetDTO;
import com.paic.mhis.hcpms.audit.dto.AuditUserInfoDTO;
import com.paic.mhis.hcpms.audit.dto.AuditiStaffInfoDTO;
import com.paic.mhis.hcpms.audit.dto.BatchSubmitResponseDTO;
import com.paic.mhis.hcpms.audit.dto.CommonInsureanceDTO;
import com.paic.mhis.hcpms.audit.dto.CommonMedicalDTO;
import com.paic.mhis.hcpms.audit.dto.CommonStaffDTO;
import com.paic.mhis.hcpms.audit.util.GetFormDateUtil;
import com.paic.mhis.hcpms.common.storage.biz.service.HcpmsStorageService;
import com.paic.mhis.hcpms.common.storage.dto.HcpmsStorageDTO;
import com.paic.mhis.hcpms.common.workflow.vo.HcpmsWorkFlowVO;
import com.paic.mhis.hcpms.trust.biz.service.IntegrityMedicalService;

@Component("auditDispatchServiceImpl")
public class AuditDispatchServiceImpl implements IAuditDispatchService {
	@Autowired
	private AuditDispatchDao auditDispatchDao;

	@Autowired
	private AuditOpinionDao auditOpinionDao;

	@Autowired
	private IntegrityMedicalService integrityMedicalService;

	@Autowired
	private AuditWorkFlowService auditWorkFlowService; // 流程服务

	public static final String type_save = "save";

	public static final String type_load = "load";

	@Autowired
	private HcpmsStorageService hcpmsStorageService;

	@Autowired
	private ICaseCommonService caseCommonService;

	@Autowired
	private CommonDAO commonDAO;

	/**
	 * 稽核经办刚
	 */
	public static final String role_name = "AUDIT_AGENT_ROLE";

	/**
	 * 根据对象编码加载医疗机构信息
	 */
	public AuditDispatchResponseDTO queryMedicalInfo(
			AuditDispatchRequestDTO requestBean) {

		AuditDispatchResponseDTO returnBean = new AuditDispatchResponseDTO();

		String problemNo = requestBean.getProblemNo();

		AuditDispatchParamter parameter = new AuditDispatchParamter();
		parameter.setProblemNo(problemNo);
		parameter.setTargetType(AuditConstants.targetType_01);
		parameter.setTaskType(requestBean.getTaskType());

		List<AuditMedicalInfoDTO> list = this.auditDispatchDao
				.queryAuditMedicalInfoDTOByProblemNo(parameter);
		int count = 0;
		if (list != null && list.size() > 0) {
			for (AuditMedicalInfoDTO bean : list) {
				bean.setCode(bean.getMedicalCode());
				bean.setSelfCode(bean.getMedicalCode());
				bean.setName(bean.getMedicalName());
			}
			count = list.size();
		}

		CommonMedicalDTO bean = new CommonMedicalDTO();
		bean.setCount(count);
		bean.setMedicalList(list);

		returnBean.setMedicalBean(bean);
		return returnBean;
	}

	/**
	 * 获取临时表中的对应的医护人员和参保人员的code
	 * 
	 * @param user
	 * @param taskCode
	 * @param targetType
	 * @return
	 */
	public List<AuditTargetDTO> getQueryTaskCode(UserDetails user,
			String taskCode, String targetType) {
		List<AuditTargetDTO> list = null;
		HcpmsStorageDTO storageBean = new HcpmsStorageDTO();
		storageBean.setChildModuleType(AuditConstants.medicalCommon);
		storageBean.setBusinessType(targetType);
		storageBean.setBusinessId(taskCode);
		storageBean.setUserId(user.getUsername());
		Object obj = this.hcpmsStorageService.getStorageDataMap(storageBean);
		if (obj != null) {
			JSONArray arrayList = JSONObject.toJavaObject(((JSONArray) obj),
					JSONArray.class);
			if (arrayList != null && arrayList.size() > 0) {

				list = new ArrayList<AuditTargetDTO>();

				for (Object currentObj : arrayList) {
					JSONObject transferJson = JSON.parseObject(currentObj
							.toString());
					AuditTargetDTO bean = JSONObject.toJavaObject(transferJson,
							AuditTargetDTO.class);
					list.add(bean);
				}

			} else if (arrayList != null && arrayList.size() == 0) {
				list = new ArrayList<AuditTargetDTO>();
			}
		}

		return list;

	}

	private String getTargetCodes(List<AuditTargetDTO> auditTargetList) {
		StringBuffer codeSql = new StringBuffer();
		for (int i = 0; i < auditTargetList.size(); i++) {
			String targetCode = auditTargetList.get(i).getTargetCode();
			if (i != auditTargetList.size() - 1) {
				codeSql.append("'" + targetCode + "',");
			} else {
				codeSql.append("'" + targetCode + "'");
			}

		}

		return codeSql.toString();
	}

	/**
	 * 根据对象编码加载医护人员
	 */
	public AuditDispatchResponseDTO queryStaffInfo(
			AuditDispatchRequestDTO requestBean, UserDetails user) {
		AuditDispatchResponseDTO returnBean = new AuditDispatchResponseDTO();

		String problemNo = requestBean.getProblemNo();

		AuditDispatchParamter parameter = new AuditDispatchParamter();

		parameter.setProblemNo(problemNo);
		parameter.setTargetType(AuditConstants.targetType_02);

		List<AuditTargetDTO> auditTargetList = this.getQueryTaskCode(user,
				problemNo, AuditConstants.targetType_02);

		// 正式库里面的医护人员
		List<AuditiStaffInfoDTO> list = null;

		if (auditTargetList != null && auditTargetList.size() > 0) {
			String codes = this.getTargetCodes(auditTargetList);
			if (StringUtils.hasText(codes)) {
				parameter.setTargetCode(codes);
				list = this.auditDispatchDao
						.queryStaffListFromTempByProblemNo(parameter);
			}

		} else if (null == auditTargetList) { // 说明没有没有暂存在临时库里面
			list = this.auditDispatchDao
					.queryAuditiStaffInfoDTOByProblemNo(parameter);
		}

		int count = 0;
		if (list != null && list.size() > 0) {

			for (AuditiStaffInfoDTO bean : list) {
				bean.setCode(bean.getMedicalCode());
				bean.setSelfCode(bean.getStaffCode());
				bean.setTempFlag(AuditConstants.opinionResult_1); // 做标是
			}
			count = list.size();
		}

		CommonStaffDTO bean = new CommonStaffDTO();
		bean.setCount(count);
		bean.setStaffList(list);

		returnBean.setStaffBean(bean);
		return returnBean;
	}

	/**
	 * 根据对象编码加载参保人信息
	 */
	public AuditDispatchResponseDTO queryInsuranceInfo(
			AuditDispatchRequestDTO requestBean, UserDetails user) {
		AuditDispatchResponseDTO returnBean = new AuditDispatchResponseDTO();
		String problemNo = requestBean.getProblemNo();

		AuditDispatchParamter parameter = new AuditDispatchParamter();

		parameter.setProblemNo(problemNo);
		parameter.setTargetType(AuditConstants.targetType_03);

		List<AuditTargetDTO> auditTargetList = this.getQueryTaskCode(user,
				problemNo, AuditConstants.targetType_03);

		// 正式库里面的参保人
		List<AuditInsuranceInfoDTO> list = null;
		if (auditTargetList != null && auditTargetList.size() > 0) {
			String codes = this.getTargetCodes(auditTargetList);

			if (StringUtils.hasText(codes)) {
				parameter.setTargetCode(codes);
				list = this.auditDispatchDao
						.queryInsuranceDTOFromTempByProblemNo(parameter);
			}

		} else if (null == auditTargetList) { // 说明没有没有暂存在临时库里面
			list = this.auditDispatchDao
					.queryAuditInsuranceInfoDTOByProblemNo(parameter);
		}

		int count = 0;
		if (list != null && list.size() > 0) {

			for (AuditInsuranceInfoDTO bean : list) {
				bean.setCode(bean.getMedicalCode());
				bean.setSelfCode(bean.getInsuranceNo());
				bean.setTempFlag(AuditConstants.opinionResult_1); // 做标是
			}
			count = list.size();
		}

		CommonInsureanceDTO bean = new CommonInsureanceDTO();

		bean.setCount(count);
		bean.setInsuranceList(list);
		returnBean.setInsuranceBean(bean);

		return returnBean;
	}

	/**
	 * 根据对象编码加载事件信息
	 */
	public AuditDispatchResponseDTO queryAuditProblemsDTO(
			AuditDispatchRequestDTO requestBean) {

		AuditDispatchResponseDTO returnBean = new AuditDispatchResponseDTO();

		String problemNo = requestBean.getProblemNo();
		AuditDispatchParamter parameter = new AuditDispatchParamter();

		parameter.setProblemNo(problemNo);

		AuditDispatchProblemDTO problemBean = this.auditDispatchDao
				.queryAuditProblemsDTOByProblemNo(parameter);

		String sourceType = problemBean.getSourceType();
		String sourceTypeDesc = this.queryAuditCodeDictionaryDesc(
				AuditConstants.CODE_TYPE_SOURCETYPE, sourceType);
		problemBean.setSourceType(sourceTypeDesc);
		returnBean.setProblemObj(problemBean);
		return returnBean;
	}

	/**
	 * 审核岗位 第一次分配任务 任务的分配 1.在意见表中增加一条记录，更新事件表的状态，开启流程
	 */
	@Transactional
	public Map<String, Object> dispatchTaskByUserCode(
			AuditDispatchUserRequestDTO requestBean, JSONObject transferJson,
			UserDetails user) throws Exception {
		Map<String, Object> result = new HashMap<String, Object>();
		Date dealDate = new Date();

		String dealDateStr = GetFormDateUtil.getStrFromDate(dealDate);

		String opertionUsername = requestBean.getOpertionUsername();
		String userCode = requestBean.getUserCode();
		String problemNo = requestBean.getProblemNo();

		AuditOpinionDTO opionionBean = new AuditOpinionDTO();

		opionionBean.setAppointFirst(userCode);
		opionionBean.setCreatedBy(opertionUsername);
		opionionBean.setOpinionType(AuditConstants.opinionType_0);
		opionionBean.setProblemNo(problemNo);
		opionionBean.setTaskType(AuditConstants.taskType_01);
		opionionBean.setOpinion(AuditConstants.opinionResult_1);
		opionionBean.setDealUserName(opertionUsername);
		opionionBean.setDealDate(dealDateStr);
		opionionBean.setIsDeleted(AuditConstants.isDeleted);

		this.auditOpinionDao.addOpinion(opionionBean);

		// 更新事件的状态
		AuditProblemsDTO problemBean = new AuditProblemsDTO();
		problemBean.setProblemCode(problemNo);
		problemBean.setProblemStatus(AuditConstants.problemStatus_2);
		problemBean.setUpdatedBy(opertionUsername);
		this.auditDispatchDao.updateAuditProblemBean(problemBean);

		// 临时扣分
		integrityMedicalService.addIntegrityPointTemps(transferJson,
				user.getUsername());

		// 启动流程
		HcpmsWorkFlowVO wfvo = new HcpmsWorkFlowVO();
		String beginType = AuditConstants.AUDIT_BEGIN_TYPE_01;
		Map<String, String> condition = new HashMap<String, String>();
		condition.put("AUDIT_BEGIN_TYPE", beginType);
		List<Authority> authorityList = user.getAuthorities();
		List<String> role = new ArrayList<String>();
		for (Authority authority : authorityList) {
			role.add(authority.getAuthority());
		}
		wfvo.setRole(role);
		wfvo.setTaskNo(problemNo);
		wfvo.setTaskType(AuditConstants.TASK_TYPE_PROBLEM);
		wfvo.setActCurrent(user.getUsername());
		wfvo.setParamValue(condition);
		wfvo.setAssigner(userCode);

		this.auditWorkFlowService.startWorkFlow(wfvo);

		result.put("flag", AuditConstants.FLAG_TURE);
		result.put("msg", AuditConstants.OPERATE_SUCCESS);

		return result;

	}

	/**
	 * 审核岗位 第二次审核分配任务 分配是否调查任务
	 * 
	 * @throws Exception
	 */
	@Transactional
	public void auditDispatchTaskSurvey(
			AuditDispatchUserRequestDTO requestBean, UserDetails user,
			JSONObject transferJson) throws Exception {

		Date dealDate = new Date();

		String dealDateStr = GetFormDateUtil.getStrFromDate(dealDate);

		String opertionUsername = requestBean.getOpertionUsername();
		String userCode = requestBean.getUserCode();
		String userBCode = requestBean.getUserBCode();
		String opinionDesc = requestBean.getOpinionDesc();

		String problemNo = requestBean.getProblemNo();

		// 更新调查初审的意见
		this.updateFirstOpinion(requestBean.getFirstOpinionDesc(), problemNo);

		AuditOpinionDTO opionionBean = new AuditOpinionDTO();

		opionionBean.setAppointFirst(userCode);
		opionionBean.setAppointSecond(userBCode);

		opionionBean.setCreatedBy(opertionUsername);
		opionionBean.setOpinionType(AuditConstants.opinionType_2);
		opionionBean.setProblemNo(problemNo);
		opionionBean.setTaskType(AuditConstants.taskType_01);
		opionionBean.setOpinion(AuditConstants.opinionResult_1);
		opionionBean.setDealUserName(opertionUsername);
		opionionBean.setDealDate(dealDateStr);
		opionionBean.setOpinionDesc(opinionDesc);
		opionionBean.setIsDeleted(AuditConstants.isDeleted);

		this.processOpinionInfo(opionionBean);

		// 更新事件的状态
		AuditProblemsDTO problemBean = new AuditProblemsDTO();
		problemBean.setProblemCode(problemNo);
		problemBean.setProblemStatus(AuditConstants.problemStatus_4);
		problemBean.setUpdatedBy(opertionUsername);

		this.auditDispatchDao.updateAuditProblemBean(problemBean);

		HcpmsStorageDTO tempObject = new HcpmsStorageDTO();
		tempObject.setBusinessId(requestBean.getProblemNo());
		tempObject.setModuleType(AuditConstants.sjModule);
		tempObject.setChildModuleType(AuditConstants.examine);
		tempObject.setBusinessType(AuditConstants.opinionType_2);
		tempObject.setUserId(user.getUsername());
		this.hcpmsStorageService.deleteStorageData(tempObject);

		integrityMedicalService.addIntegrityPointTemps(transferJson,
				user.getUsername());// 临时扣分
		this.caseCommonService.deleteAuditCasePoint(requestBean.getProblemNo(),
				user.getUsername());

		// 结束当前的流程
		Map<String, String> condition = new HashMap<String, String>();
		condition.put(AuditConstants.AUDIT_PROBLEM_JUDGE_TYPE,
				AuditConstants.AUDIT_PROBLEM_JUDGE_TYPE_01);
		this.auditWorkFlowService.processWorkFlow(problemNo, user, userCode,
				condition, AuditConstants.TASK_TYPE_PROBLEM);

	}

	/**
	 * 处理意见1.先查询是否存在当前意见，然后在更新
	 * 
	 * @param opinion
	 */
	@Transactional
	private void processOpinionInfo(AuditOpinionDTO opinion) {

		List<AuditOpinionDTO> opinionList = this.auditOpinionDao
				.queryAuditOpinionDTOInfo(opinion);
		if (opinionList != null && opinionList.size() > 0) {
			this.auditOpinionDao.updateAuditOpinionDTOInfo(opinion);
		} else {
			this.auditOpinionDao.addOpinion(opinion);
		}

	}

	/**
	 * 审核岗位 第二次审核分配任务 分配是否调查 选择不同意调查 1.将意见保存到意见表中 2.更改事件状态为结束 3.更改结束当前流程
	 */
	@Transactional
	public Map<String, Object> aduitSuveryDisagreeConfirm(
			AuditDispatchUserRequestDTO requestBean, JSONObject transferJson,
			UserDetails user, Map<String, Object> result) throws Exception {
		Date dealDate = new Date();

		String dealDateStr = GetFormDateUtil.getStrFromDate(dealDate);

		String opertionUsername = requestBean.getOpertionUsername();
		String opinionDesc = requestBean.getOpinionDesc();

		String problemNo = requestBean.getProblemNo();

		// 更新调查初审的意见
		this.updateFirstOpinion(requestBean.getFirstOpinionDesc(), problemNo);

		AuditOpinionDTO opionionBean = new AuditOpinionDTO();

		opionionBean.setCreatedBy(opertionUsername);
		opionionBean.setOpinionType(AuditConstants.opinionType_2);
		opionionBean.setProblemNo(problemNo);
		opionionBean.setTaskType(AuditConstants.taskType_01);
		opionionBean.setOpinion(requestBean.getOpinion());
		opionionBean.setDealUserName(opertionUsername);
		opionionBean.setDealDate(dealDateStr);
		opionionBean.setOpinionDesc(opinionDesc);
		opionionBean.setIsDeleted(AuditConstants.isDeleted);

		this.processOpinionInfo(opionionBean);

		// 更新事件的状态
		AuditProblemsDTO problemBean = new AuditProblemsDTO();
		problemBean.setProblemCode(problemNo);
		problemBean.setProblemStatus(AuditConstants.problemStatus_7);
		problemBean.setUpdatedBy(opertionUsername);

		// 判断是暂存还是正常
		this.auditDispatchDao.updateAuditProblemBean(problemBean);

		HcpmsStorageDTO tempObject = new HcpmsStorageDTO();
		tempObject.setBusinessId(requestBean.getProblemNo());
		tempObject.setModuleType(AuditConstants.sjModule);
		tempObject.setChildModuleType(AuditConstants.examine);
		tempObject.setBusinessType(AuditConstants.opinionType_2);
		tempObject.setUserId(user.getUsername());

		this.hcpmsStorageService.deleteStorageData(tempObject);

		integrityMedicalService.addIntegrityPointTemps(transferJson,
				user.getUsername());// 临时扣分
		this.caseCommonService.deleteAuditCasePoint(requestBean.getProblemNo(),
				user.getUsername());

		// 结束当前的流程
		Map<String, String> condition = new HashMap<String, String>();
		condition.put(AuditConstants.AUDIT_PROBLEM_JUDGE_TYPE,
				AuditConstants.AUDIT_PROBLEM_JUDGE_TYPE_02);
		this.auditWorkFlowService.processWorkFlow(problemNo, user, condition,
				AuditConstants.TASK_TYPE_PROBLEM);

		result.put("state", AuditConstants.FLAG_TURE);
		result.put("msg", AuditConstants.OPERATE_SUCCESS);
		return result;
	}

	public String queryAuditCodeDictionaryDesc(String codeType, String code) {
		AuditCodeDictionary dictionary = new AuditCodeDictionary();
		dictionary.setCodeType(codeType);
		dictionary.setCodeNo(code);
		AuditCodeDictionary bean = this.auditDispatchDao
				.queryAuditCodeDictionaryByTypeAndCode(dictionary);
		if (bean != null) {
			return bean.getCodeDesc();
		} else {
			return "";
		}

	}

	/**
	 * 根据角色名称加载该角色下的用户信息
	 */
	public List<AuditUserInfoDTO> queryAuditUserInfoByRoleName(String roleName) {

		return this.auditDispatchDao.queryAuditUserInfoDTO(roleName);
	}

	/**
	 * 处理更新上个岗位的意见信息
	 * 
	 * @param firstOpinionDesc
	 * @param problemNo
	 */
	@Transactional
	private void updateFirstOpinion(String firstOpinionDesc, String problemNo) {
		AuditOpinionDTO opinion = new AuditOpinionDTO();
		opinion.setProblemNo(problemNo);
		opinion.setTaskType(AuditConstants.taskType_01);
		opinion.setOpinionType(AuditConstants.opinionType_1);
		opinion.setOpinionDesc(firstOpinionDesc);
		this.auditOpinionDao.updateAuditOpinionDTOInfo(opinion);
	}

	/**
	 * 处理事件初审的审核的暂存
	 */
	@Transactional
	@Override
	public AuditDispatchUserResponseDTO processTempSave(
			AuditDispatchUserRequestDTO requestBean, String type,
			JSONObject transferJson, String userName) throws Exception {
		AuditDispatchUserResponseDTO responseBean = new AuditDispatchUserResponseDTO();
		// 暂存调查审核
		if (type_save.equals(type)) {
			// 更新调查初审的意见
			HcpmsStorageDTO tempObject = new HcpmsStorageDTO();
			tempObject.setBusinessId(requestBean.getProblemNo());
			tempObject.setModuleType(AuditConstants.sjModule);
			tempObject.setChildModuleType(AuditConstants.examine);
			tempObject.setBusinessType(AuditConstants.opinionType_2);
			tempObject.setUserId(userName);
			tempObject.setDataMap(requestBean);
			this.hcpmsStorageService.saveStorageData(tempObject, false);

			// 暂存扣分
			this.caseCommonService.saveAuditCasePoint(
					requestBean.getProblemNo(), transferJson, userName);

		}

		// 初始化暂存信息
		if (type_load.equals(type)) {
			HcpmsStorageDTO tempObject = new HcpmsStorageDTO();
			tempObject.setBusinessId(requestBean.getProblemNo());
			tempObject.setModuleType(AuditConstants.sjModule);
			tempObject.setChildModuleType(AuditConstants.examine);
			tempObject.setBusinessType(AuditConstants.opinionType_2);
			tempObject.setUserId(userName);

			Object obj = this.hcpmsStorageService.getStorageDataMap(tempObject);
			if (obj != null) {
				AuditDispatchUserRequestDTO currentObj = JSONObject
						.toJavaObject(((JSONObject) obj),
								AuditDispatchUserRequestDTO.class);

				AuditOpinionDTO loadOpinion = new AuditOpinionDTO();
				loadOpinion.setOpinion(currentObj.getOpinion());
				loadOpinion.setOpinionDesc(currentObj.getOpinionDesc());
				responseBean.setAuditOpinion(loadOpinion);

			}

		}
		return responseBean;
	}

	/**
	 * 批量处理事件审核的业务逻辑
	 * 
	 * @throws Exception
	 */
	@Transactional
	@Override
	public BatchSubmitResponseDTO processBatchSubmitInfo(String[] listCodes,
			UserDetails user, String opinion, String opinionDesc)
			throws Exception {
		BatchSubmitResponseDTO bean = new BatchSubmitResponseDTO();
		if (StringUtils.hasText(opinion)
				&& AuditConstants.reviewResult_1.equals(opinion)) { // 需要调查
			bean = this.processBatchSubmitAgressInfo(listCodes, user, opinion,
					opinionDesc);
		} else if (StringUtils.hasText(opinion)
				&& !AuditConstants.reviewResult_1.equals(opinion)) { // 无需调查或者是转到其他部门
			bean = this.batchSubmitDisAgressInfo(listCodes, user, opinion,
					opinionDesc);
		}

		return bean;

	}

	/**
	 * 随机生成要分配的经办刚人员信息
	 * 
	 * @param username
	 * @return
	 */
	private AuditUserInfoDTO getRandomOpertionUserName(String username) {

		AuditUserInfoDTO returnBean = null;

		List<AuditUserInfoDTO> list = this
				.queryAuditUserInfoByRoleName(role_name);
		List<AuditUserInfoDTO> tempList = new ArrayList<AuditUserInfoDTO>();

		if (StringUtils.hasText(username)) {
			for (AuditUserInfoDTO bean : list) {
				String currentUsername = bean.getUsername();
				if (!username.equals(currentUsername)) {
					tempList.add(bean);
				}
			}

			returnBean = this.getRandomFromList(tempList);
		} else {

			returnBean = this.getRandomFromList(list);

		}

		return returnBean;
	}

	/**
	 * 生成随机数
	 * 
	 * @param tempList
	 * @return
	 */
	private AuditUserInfoDTO getRandomFromList(List<AuditUserInfoDTO> tempList) {
		AuditUserInfoDTO randomBean = null;
		if (tempList != null && tempList.size() > 0) {
			int count = tempList.size();
			// int num = (int) (Math.random() * count);
			int num = new Random().nextInt(count);
			randomBean = tempList.get(num);
		}

		return randomBean;
	}

	/**
	 * 处理批量事件审核中意见类型是需要调查的逻辑
	 * 
	 * @param problemNo
	 * @param user
	 * @return
	 * @throws Exception
	 */
	@Transactional
	private BatchSubmitResponseDTO processBatchSubmitAgressInfo(
			String[] listCodes, UserDetails user, String opinion,
			String opinionDesc) throws Exception {
		BatchSubmitResponseDTO returnBean = new BatchSubmitResponseDTO();
		if (listCodes != null && listCodes.length > 0) {
			AuditUserInfoDTO userAName = this.getRandomOpertionUserName(""); // 经办岗A
			AuditUserInfoDTO userBName = this
					.getRandomOpertionUserName(userAName.getUsername()); // 经办岗B

			for (String problemNo : listCodes) {

				AuditProblemsDTO problemBean = new AuditProblemsDTO();
				problemBean.setProblemCode(problemNo);

				AuditProblemsDTO rsl = (AuditProblemsDTO) commonDAO.get(
						"auditProblemsDao.queryAuditProblemsDetail",
						problemBean);
				if (rsl.getProblemStatus().equals(
						AuditConstants.problemStatus_4)) {
					continue;
				}

				String firstOpinionDesc = this
						.getBatchSubmitFirstOpinion(problemNo); // 第一次审核的意见描述

				JSONObject transferJson = this.caseCommonService
						.queryBatchOpertionAuditCasePoint(problemNo,
								user.getUsername());

				AuditDispatchUserRequestDTO processBean = new AuditDispatchUserRequestDTO();
				processBean.setOpertionUsername(user.getUsername());
				processBean.setFirstOpinionDesc(firstOpinionDesc);
				processBean.setUserCode(userAName.getUsername());
				processBean.setUserBCode(userBName.getUsername());
				processBean.setOpinion(opinion);
				processBean.setOpinionDesc(opinionDesc);
				processBean.setProblemNo(problemNo);
				// 审核
				this.auditDispatchTaskSurvey(processBean, user, transferJson);
				// 处理公共的医务人员和参保人信息
				this.caseCommonService.batchOpertionMedicalCommon(problemNo,
						AuditConstants.taskType_01, user.getUsername());

			}
			returnBean.setFlag(true);
			returnBean.setMessage("操作成功" + listCodes.length + "条,失败0条!分配经办刚A["
					+ userAName.getDisplayName() + "],经办刚B["
					+ userBName.getDisplayName() + "]");
		}

		return returnBean;
	}

	private String getBatchSubmitFirstOpinion(String problemNo) {
		AuditOpinionDTO opinion = new AuditOpinionDTO();
		opinion.setProblemNo(problemNo);
		opinion.setTaskType(AuditConstants.taskType_01);
		opinion.setOpinionType(AuditConstants.opinionType_1);
		AuditOpinionDTO opinionBean = this.auditOpinionDao
				.getOpinionByType(opinion);
		if (opinionBean != null) {
			return opinionBean.getOpinionDesc();
		} else {
			return "";
		}

	}

	/**
	 * 处理批量事件审核中意见类型是无需调查或者是转入其他部门的逻辑
	 * 
	 * @param problemNo
	 * @param user
	 * @return
	 * @throws Exception
	 */

	@Transactional
	private BatchSubmitResponseDTO batchSubmitDisAgressInfo(String[] listCodes,
			UserDetails user, String opinion, String opinionDesc)
			throws Exception {
		BatchSubmitResponseDTO returnBean = new BatchSubmitResponseDTO();
		if (listCodes != null && listCodes.length > 0) {

			for (String problemNo : listCodes) {

				AuditProblemsDTO problemBean = new AuditProblemsDTO();
				problemBean.setProblemCode(problemNo);

				AuditProblemsDTO rsl = (AuditProblemsDTO) commonDAO.get(
						"auditProblemsDao.queryAuditProblemsDetail",
						problemBean);
				if (rsl.getProblemStatus().equals(
						AuditConstants.problemStatus_7)) {
					continue;
				}

				Map<String, Object> result = new HashMap<String, Object>();

				String firstOpinionDesc = this
						.getBatchSubmitFirstOpinion(problemNo); // 第一次审核的意见描述

				JSONObject transferJson = this.caseCommonService
						.queryBatchOpertionAuditCasePoint(problemNo,
								user.getUsername());

				AuditDispatchUserRequestDTO processBean = new AuditDispatchUserRequestDTO();
				processBean.setOpertionUsername(user.getUsername());
				processBean.setFirstOpinionDesc(firstOpinionDesc);
				processBean.setOpinion(opinion);
				processBean.setOpinionDesc(opinionDesc);
				processBean.setProblemNo(problemNo);
				// 审核
				this.aduitSuveryDisagreeConfirm(processBean, transferJson,
						user, result);
				// 处理公共的医务人员和参保人信息
				this.caseCommonService.batchOpertionMedicalCommon(problemNo,
						AuditConstants.taskType_01, user.getUsername());
			}

			returnBean.setFlag(true);
			returnBean.setMessage("操作成功" + listCodes.length + "条,失败0条!");
		}

		return returnBean;
	}

	/**
	 * 事件管理 批量分配
	 */
	@Transactional
	@Override
	public Map<String, Object> problemManagementBatchSubmit(
			String[] problemCodeList, UserDetails user) throws Exception {
		Map<String, Object> result = new HashMap<String, Object>();
		result.put("state", AuditConstants.FLAG_FALSE);
		result.put("msg", AuditConstants.OPERATE_SUCCESS);
		if (problemCodeList == null || problemCodeList.length == 0) {
			result.put("state", AuditConstants.FLAG_FALSE);
			result.put("msg", AuditConstants.OPERATE_SUCCESS);
			return result;
		}
		AuditDispatchUserRequestDTO vo = new AuditDispatchUserRequestDTO();
		vo.setOpertionUsername(user.getUsername());
		// List<AuditUserInfoDTO> userlist =
		// this.auditDispatchService.queryAuditUserInfoByRoleName(role_name);
		List<AuditUserInfoDTO> userlist = this.auditDispatchDao
				.queryAuditUserInfoDTO(role_name);
		if (userlist == null || userlist.size() == 0) {
			result.put("state", AuditConstants.FLAG_FALSE);
			result.put("msg", AuditConstants.OPERATE_SUCCESS + "未找到经办岗");
			return result;
		}
		StringBuffer sb = new StringBuffer();
		int successCount = problemCodeList.length;
		for (String problemCode : problemCodeList) {
			AuditUserInfoDTO u = getRandomUser(userlist);
			vo.setProblemNo(problemCode);
			vo.setUserCode(u.getUsername());// 需要每次去查找，而非从前台提供的
			try {
				this.dispatchTaskByUserCode(vo, null, user);
			} catch (Exception e) {
				e.printStackTrace();
				successCount--;
			}
			sb.append(" 事件" + problemCode + "，经办人：" + u.getDisplayName()
					+ " 编号：" + u.getUsername());
		}
		result.put("state", AuditConstants.FLAG_TURE);
		result.put("msg", AuditConstants.OPERATE_SUCCESS + " 成功" + successCount
				+ "条，失败" + (problemCodeList.length - successCount)
				+ "条。人员分配情况如下： " + sb.toString());
		return result;
	}

	private AuditUserInfoDTO getRandomUser(List<AuditUserInfoDTO> userlist) {
		// int randomIndex = (int) (userlist.size() * Math.random());
		int randomIndex = new Random().nextInt(userlist.size());
		return userlist.get(randomIndex);
	}

}
